<template>
    <div class="content">
        <div class="menu-properties">
            <div class="wechat">
                <div class="wechat-header"></div>
                <div class="wechat-body"></div>
                <div class="wechat-footer">
                    <div class="icon">
                        <img src="https://image.lutongjiakao.com/system/3521950b01f247db85661f7bcc840b94.png" alt="">
                    </div>
                    <div class="addMent">
                        <div v-for="(ele, index) in menuList" :key="index" class="itemMent"
                            :class="{ 'itemMent-active': activeMenuIndex === index }" @click="selectParent(index)">
                            <div class="menu-name">{{ ele.name }}</div>
                            <div class="child-menu-container">
                                <div v-for="(val, i) in ele.subButtons" :key="i" class="child-menu-item"
                                    :class="{ 'child-menu-item-active': activeMenuIndex === index && activeChildMenuIndex === i }"
                                    @click.stop="selectChild(index, i)">
                                    {{ val.name }}
                                    <div class="delChildIcon" @click.stop="delChild(index, i)">×</div>
                                </div>
                                <div v-if="ele.subButtons.length < 5" class="add-child" @click="addChild(index)">
                                    +
                                </div>
                            </div>
                            <div class="delIcon" @click.stop="delItem(index)">×</div>
                        </div>
                        <div class="add" v-if="menuList.length < 3" @click="addItem">+</div>
                    </div>
                </div>
            </div>
            <div class="menu-form" v-if="menuList.length">
                <div class="form-title">菜单属性</div>
                <!-- 一级 -->
                <el-form label-width="107" v-if="!distinguish">
                    <el-form-item label="菜单名称">
                        <el-input class="w270" v-model="menuList[activeMenuIndex].name"></el-input>
                    </el-form-item>
                    <el-form-item label="菜单动作" v-if="!menuList[activeMenuIndex].subButtons.length">
                        <el-radio-group v-model="menuList[activeMenuIndex].type">
                            <el-radio value="click">发送消息</el-radio>
                            <el-radio value="view">跳转网页</el-radio>
                            <el-radio value="miniprogram">小程序</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="添加发送内容"
                        v-if="menuList[activeMenuIndex].type === 'click' || menuList[activeMenuIndex].type === 'media_id'">
                        <div class="editor-box">
                            <div class="wechat-wechat-editor">
                                <div class="editor-type">
                                    <div class="itemType" v-for="(item, index) in sendList" :key="index"
                                        :class="{ active: sendIndex === index }" @click="sendChange(index)">
                                        {{ item }}
                                    </div>
                                </div>
                                <div class="editor-info">
                                    <div class="editor-video" v-if="sendIndex === 1">
                                        <div class="addIcon" v-if="!selectedImages.length" @click="openImageSelector">+
                                        </div>
                                        <div class="image-preview-list" v-if="selectedImages.length">
                                            <div v-for="(img, idx) in selectedImages" :key="img.url"
                                                class="image-preview-item">
                                                <img :src="img.url" class="preview-img" />
                                                <span class="delColor" @click="removeImage(idx)">删除</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div v-if="keyword && sendIndex === 0">
                                        <span>{{ keyword }}</span>
                                        <span class="delColor" @click="delText(1)">删除</span>
                                        <span class="delColor" @click="openSend">重新选择</span>
                                    </div>
                                    <div class="editor-video" @click="openSend" v-if="!keyword && sendIndex === 0">
                                        <div class="addIcon">+</div>
                                        <div>选择关键字</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item label="跳转网页" v-if="menuList[activeMenuIndex].type === 'view'">
                        <el-input style="max-width: 450px" placeholder="请填写以http://或https://开头的有效链接"
                            v-model="menuList[activeMenuIndex].url">
                            <template #append>
                                <div>选择链接</div>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="APPID" v-if="menuList[activeMenuIndex].type === 'miniprogram'">
                        <el-input style="max-width: 450px" placeholder="请确保公众号与小程序已绑定"
                            v-model="menuList[activeMenuIndex].appId" />
                    </el-form-item>
                    <el-form-item label="页面地址" v-if="menuList[activeMenuIndex].type === 'miniprogram'">
                        <el-input style="max-width: 450px" placeholder="请填写跳转页面的小程序访问路径"
                            v-model="menuList[activeMenuIndex].pagePath">
                            <template #append>
                                <div>选择链接</div>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="URL" v-if="menuList[activeMenuIndex].type === 'miniprogram'">
                        <el-input style="max-width: 450px" placeholder="无法打开小程序时跳转的页面"
                            v-model="menuList[activeMenuIndex].url">
                        </el-input>
                    </el-form-item>
                </el-form>
                <!-- 二级 -->
                <el-form label-width="107" v-else>
                    <el-form-item label="菜单名称">
                        <el-input class="w270"
                            v-model="menuList[activeMenuIndex].subButtons[activeChildMenuIndex].name"></el-input>
                    </el-form-item>
                    <el-form-item label="菜单动作">
                        <el-radio-group v-model="menuList[activeMenuIndex].subButtons[activeChildMenuIndex].type">
                            <el-radio value="click">发送消息</el-radio>
                            <el-radio value="view">跳转网页</el-radio>
                            <el-radio value="miniprogram">小程序</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="跳转网页"
                        v-if="menuList[activeMenuIndex].subButtons[activeChildMenuIndex].type === 'view'">
                        <el-input style="max-width: 450px" placeholder="请填写以http://或https://开头的有效链接"
                            v-model="menuList[activeMenuIndex].subButtons[activeChildMenuIndex].url">
                            <template #append>
                                <div @click="showLinkDataDialog = true">选择链接</div>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="APPID"
                        v-if="menuList[activeMenuIndex].subButtons[activeChildMenuIndex].type === 'miniprogram'">
                        <el-input style="max-width: 450px" placeholder="请确保公众号与小程序已绑定"
                            v-model="menuList[activeMenuIndex].subButtons[activeChildMenuIndex].appId" />
                    </el-form-item>
                    <!-- 新增：区分页面地址与小程序URL，只做前端输入区分，真实参数保存时映射为url -->
                    <el-form-item label="页面地址"
                        v-if="menuList[activeMenuIndex].subButtons[activeChildMenuIndex].type === 'miniprogram'">
                        <el-input style="max-width: 450px" placeholder="填写小程序路径，如 pages/index/index"
                            v-model="menuList[activeMenuIndex].subButtons[activeChildMenuIndex].miniPagePath" clearable>
                            <template #append>
                                <div @click="showLinkDataDialog = true">选择链接</div>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="小程序URL"
                        v-if="menuList[activeMenuIndex].subButtons[activeChildMenuIndex].type === 'miniprogram'">
                        <el-input style="max-width: 450px" placeholder="无法打开小程序时跳转的链接"
                            v-model="menuList[activeMenuIndex].subButtons[activeChildMenuIndex].miniUrl" clearable>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="添加发送内容" v-if="menuList[activeMenuIndex]
                        && menuList[activeMenuIndex].subButtons
                        && menuList[activeMenuIndex].subButtons[activeChildMenuIndex]
                        && (menuList[activeMenuIndex].subButtons[activeChildMenuIndex].type === 'click'
                            || menuList[activeMenuIndex].subButtons[activeChildMenuIndex].type === 'media_id')">
                        <div class="editor-box">
                            <div class="wechat-wechat-editor">
                                <div class="editor-type">
                                    <div class="itemType" v-for="(item, index) in sendList" :key="index"
                                        :class="{ active: sendIndex === index }" @click="sendChange(index)">
                                        {{ item }}
                                    </div>
                                </div>
                                <div class="editor-info">
                                    <div class="editor-video" v-if="sendIndex === 1">
                                        <div class="addIcon" v-if="!selectedImages.length" @click="openImageSelector">+
                                        </div>
                                        <div class="image-preview-list" v-if="selectedImages.length">
                                            <div v-for="(img, idx) in selectedImages" :key="img.url"
                                                class="image-preview-item">
                                                <img :src="img.url" class="preview-img" />
                                                <span class="delColor" @click="removeImage(idx)">删除</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div v-if="keyword && sendIndex === 0">
                                        <span>{{ keyword }}</span>
                                        <span class="delColor" @click="delText(1)">删除</span>
                                        <span class="delColor" @click="openSend">重新选择</span>
                                    </div>
                                    <div class="editor-video" @click="openSend" v-if="!keyword && sendIndex === 0">
                                        <div class="addIcon">+</div>
                                        <div>选择关键字</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <el-button type="primary" style="width: 90px;margin-left: 12px;margin-top: 200px;" @click="handleSave"
            :loading="btnLoding">
            保存
        </el-button>
        <el-dialog v-model="sendModal" title="关键字选择器" :close-on-click-modal="false">
            <art-table :data="tableData" :loading="tableLoading" :currentPage="pageNum" :pageSize="pageSize"
                :total="pageTotal" @current-change="currentChange" @size-change="sizeChange">
                <template #default>
                    <el-table-column width="50">
                        <template #default="scope">
                            <el-radio-group v-model="selectedRowIndex"
                                @change="handleRowClick(scope.row, scope.row.id)">
                                <el-radio :value="scope.row.id"></el-radio>
                            </el-radio-group>
                        </template>
                    </el-table-column>
                    <el-table-column label="规则名称" prop="name" align="center" />
                    <el-table-column label="关键词" prop="matchValue" align="center" v-if="sendIndex === 0" />
                    <el-table-column label="回复内容" prop="replyContent" align="center" />
                </template>
            </art-table>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="sendModal = false">取消</el-button>
                    <el-button type="primary" @click="confirmSendSelection">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <ChoiceLink v-if="showLinkDataDialog" :show-link-dialog="showLinkDataDialog"
            @close-dialog="handleCloseLinkDialog" />
        <image-selected-dialog v-if="showImageChooseDialog" :single-type="selectImageSingle"
            :show-image-choose-dialog="showImageChooseDialog" @close-dialog="handleCloseImageDialog"
            :operationType="false"></image-selected-dialog>
    </div>
</template>
<script setup lang="ts">
import { customizeMenuList, getAutoReplyPage, customMenuCreate, uploadMaterial, getMaterial } from '@/api/marketing'
import {
    getGZHAuthorizerInfo
} from '@/api/ApiList'
import ImageSelectedDialog from '@/views/decoration/diyComponents/ImageSelectedDialog.vue'
import { onMounted, ref } from 'vue'
import ChoiceLink from './choiceLink.vue'

const menuRadio = ref('')
const sendList = ref(['关键字', '图片'])
const sendIndex = ref(0) //发送内容切换，默认选中关键字
const activeMenuIndex = ref(0) //选中的哪一个
const menuList = ref<any>([])
const activeChildMenuIndex = ref(-1) // 选中的子级菜单
const distinguish = ref(false) //判断是父级还是子级的
const sendModal = ref(false)
const tableLoading = ref(false)
const pageNum = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const tableData = ref([])
const defaultText = ref('')
const keyword = ref('')
const btnLoding = ref(false)
const showLinkDataDialog = ref(false)
// 图片选择弹窗
const showImageChooseDialog = ref(false)
const selectImageSingle = ref(true)

// 新增：存储上传后的图片信息（字符串url）列表
const selectedImages = ref<{ url: string }[]>([])

// 公共方法：通过 mediaId 获取图片数据进行回显
const loadImageByMediaId = async (mediaId: string) => {
    if (!mediaId) {
        selectedImages.value = []
        return
    }
    try {
        const res = await getMaterial({
            mediaId: mediaId,
            type: 'image',
        })
        if (res.code === '00000' && res.data) {
            // 处理 base64 格式的图片数据
            const base64Data = res.data.content
            let imageUrl = ''

            if (base64Data) {
                // 如果 base64 数据没有 data:image 前缀，则添加
                if (base64Data.startsWith('data:image')) {
                    imageUrl = base64Data
                } else {
                    // 根据 base64 数据的前几个字符判断图片格式
                    let mimeType = 'image/jpeg' // 默认 jpeg
                    if (base64Data.startsWith('/9j/') || base64Data.startsWith('/9j4AAQSkZJRgABA')) {
                        mimeType = 'image/jpeg'
                    } else if (base64Data.startsWith('iVBORw0KGgo')) {
                        mimeType = 'image/png'
                    } else if (base64Data.startsWith('R0lGOD')) {
                        mimeType = 'image/gif'
                    } else if (base64Data.startsWith('UklGR')) {
                        mimeType = 'image/webp'
                    }

                    imageUrl = `data:${mimeType};base64,${base64Data}`
                }
            }

            selectedImages.value = [{
                url: imageUrl
            }]
        } else {
            selectedImages.value = []
        }
    } catch (error) {
        selectedImages.value = []
    }
}

function removeImage(idx: number) {
    selectedImages.value.splice(idx, 1)
    // 如需同步移除菜单结构里的图片引用也在这里处理
    if (!distinguish.value) {
        menuList.value[activeMenuIndex.value].mediaId = ''
    } else {
        menuList.value[activeMenuIndex.value].subButtons[activeChildMenuIndex.value].mediaId = ''
    }
}

function openImageSelector() {
    // 当选择图片时，自动设置菜单动作为"发送消息"
    if (!distinguish.value) {
        // 一级菜单
        menuList.value[activeMenuIndex.value].type = 'click'
    } else {
        // 二级菜单
        menuList.value[activeMenuIndex.value].subButtons[activeChildMenuIndex.value].type = 'click'
    }

    // 仅允许单选
    selectImageSingle.value = true
    showImageChooseDialog.value = true
}

async function handleCloseImageDialog(value: any) {
    // 支持单选/多选，和取消
    showImageChooseDialog.value = false;
    if (!value || value === false) return;

    // 允许支持单张或多张图片，但此处只取第一张
    const files = Array.isArray(value) ? value : [value];
    const firstFile = files[0];
    if (!firstFile || !firstFile.fileUrl) return;

    const fileUrl = firstFile.fileUrl;
    try {
        const res = await uploadMaterial({ fileUrl, type: 'image' });
        if (res.code !== '00000') {
            ElMessage.error(res.msg || '图片上传失败');
            return;
        }

        const mediaId = res.data.mediaId;
        selectedImages.value = [{ url: fileUrl }];
        if (!distinguish.value) {
            const menu = menuList.value[activeMenuIndex.value];
            if (menu) {
                menu.mediaId = mediaId;
                menu.type = 'media_id';
            }
        } else {
            const parentMenu = menuList.value[activeMenuIndex.value];
            const childMenu = parentMenu?.subButtons?.[activeChildMenuIndex.value];
            if (childMenu) {
                childMenu.mediaId = mediaId;
                childMenu.type = 'media_id';
            }
        }
    } catch (error) {
        ElMessage.error('图片处理失败');
    }
}

function handleCloseLinkDialog(value: any) {
    if (value) {
        const storeId = localStorage.getItem('lty-store-id')
        if (distinguish.value) { // 二级菜单
            const subBtn = menuList.value[activeMenuIndex.value].subButtons[activeChildMenuIndex.value];
            if (subBtn.type === 'view') {
                subBtn.url = `https://www.lutongjiakao.com/lvh5/#/${value.routePath}?store_id=${storeId}&gzh_appid=${gzhAppId.value}`
            } else if (subBtn.type === 'miniprogram') {
                // 只设置 miniPagePath（页面地址）字段
                subBtn.miniPagePath = `${value.routePath}`
            }
        } else { // 一级菜单
            if (menuList.value[activeMenuIndex.value].type === 'view') {
                menuList.value[activeMenuIndex.value].url = `https://www.lutongjiakao.com/lvh5/#/${value.routePath}?store_id=${storeId}&gzh_appid=${gzhAppId.value}`
            } else {
                menuList.value[activeMenuIndex.value].pagePath = `${value.routePath}`
            }
        }
    }
    showLinkDataDialog.value = false
}

// 新增：弹框表格单选相关
const selectedRowIndex = ref(-1)
const selectedRowData = ref<any>(null)

const getData = async () => {
    try {
        const res = await customizeMenuList()
        if (res.code === '00000') {
            // 回显处理：对于二级的 miniprogram，将pagePath和url分别映射到miniPagePath与miniUrl，方便前端分开绑定
            menuList.value = (res.data.menu.buttons || []).map((btn: any) => ({
                ...btn,
                subButtons: (btn.subButtons || []).map((sub: any) => {
                    if (sub.type === 'miniprogram') {
                        // 兼容历史数据：初始化miniprogram时分离
                        return {
                            ...sub,
                            miniPagePath: sub.pagePath || '',
                            miniUrl: sub.url || '',
                        }
                    }
                    return sub
                })
            }))
            // 默认选中并回显第一个一级菜单内容
            if (menuList.value.length) {
                await selectParent(0)
            }
        } else {
            ElMessage.error(res.msg)
        }
    } catch { } finally { }
}

//父级新增、删除
let menuKeyCounter = 0; // 用于生成唯一key

const addItem = () => {
    menuList.value.push({
        appId: '',
        articleId: '',
        key: `menu_key_${Date.now()}_${menuKeyCounter++}`,
        mediaId: '',
        name: '未命名',
        pagePath: '',
        subButtons: [],
        type: 'click',
        url: ''
    });
    // 添加发送内容默认选中关键字
    sendIndex.value = 0;
}

const delItem = (i: number) => {
    menuList.value.splice(i, 1)
    // 如果删除的是当前激活的父级，重置子级激活
    if (activeMenuIndex.value === i) {
        activeChildMenuIndex.value = -1
    }
}

// 子级新增、删除
const addChild = (index: number) => {
    if (menuList.value[index].subButtons.length < 5) {
        menuList.value[index].subButtons.push({
            appId: '',
            articleId: '',
            key: '',
            mediaId: '',
            name: '未命名',
            // 注意：下列为区分配置
            miniPagePath: '',
            miniUrl: '',
            pagePath: '',
            subButtons: [],
            type: 'click',
            url: ''
        });
        // 子菜单添加时，“添加发送内容”默认选中关键字
        sendIndex.value = 0;
    }
    // 优化：重置父级菜单的相关字段为初始值
    Object.assign(menuList.value[index], {
        appId: '',
        articleId: '',
        key: '',
        mediaId: '',
        pagePath: '',
        type: '',
        url: ''
    });
}

const delChild = (index: number, i: number) => {
    menuList.value[index].subButtons.splice(i, 1)
    if (activeMenuIndex.value === index && activeChildMenuIndex.value === i) {
        activeChildMenuIndex.value = -1
        distinguish.value = false
        // 选回父级，并触发其数据回显，确保右侧内容刷新为父级菜单
        selectParent(index)
    } else if (activeMenuIndex.value === index && activeChildMenuIndex.value > i) {
        // 如果当前激活二级菜单在被删除项后面，索引要向前移动一位
        activeChildMenuIndex.value = activeChildMenuIndex.value - 1
    }
}

const selectParent = async (index: number) => {
    activeMenuIndex.value = index
    distinguish.value = false
    activeChildMenuIndex.value = -1
    const parent = menuList.value[index];
    const key = parent.key || '';
    const hasImage = Boolean(parent.mediaId)
    const isKeyword = key.includes('g_'); // 0 关键字, 1 图片
    // 默认选中关键字
    sendIndex.value = 0;

    // 如果有图片，确保菜单类型为发送消息类型，并且切换到图片tab
    if (hasImage) {
        parent.type = 'click'
        sendIndex.value = 1;
    } else if (isKeyword) {
        sendIndex.value = 0;
    } else {
        sendIndex.value = 0;
    }

    await getSendData();
    // 优化：避免重复 split 和查找
    const keyParts = key.split('_');
    targetId.value = keyParts[2] || '';
    const foundItem: any = tableData.value.find((item: any) => String(item.id) === String(targetId.value));
    if (hasImage) {
        await loadImageByMediaId(parent.mediaId)
    } else if (isKeyword) {
        keyword.value = foundItem ? (foundItem.matchValue || foundItem.name || '') : '';
    } else {
        defaultText.value = foundItem ? (foundItem.replyContent || foundItem.name || '') : '';
    }
    menuRadio.value = ''
}

const targetId = ref('')
const selectChild = async (parentIdx: number, childIdx: number) => {
    activeMenuIndex.value = parentIdx;
    activeChildMenuIndex.value = childIdx;
    distinguish.value = true;
    const child = menuList.value[parentIdx].subButtons[childIdx];

    // 清空关键字和默认文本，防止上次点击的子级数据回显到新子级
    keyword.value = '';
    defaultText.value = '';
    selectedImages.value = [];

    // 如果是miniprogram类型，前端分开管理 两个字段
    if (child.type === 'miniprogram') {
        if (!('miniPagePath' in child)) {
            child.miniPagePath = child.pagePath || ''
        }
        if (!('miniUrl' in child)) {
            child.miniUrl = child.url || ''
        }
    }

    const key = child.key || '';
    const hasImage = Boolean(child.mediaId)
    const isKeyword = key.includes('g_'); // 0 关键字, 1 图片
    // 默认选中关键字
    sendIndex.value = 0;

    // 如果有图片，确保菜单类型为发送消息类型，并且切换到图片tab
    if (hasImage) {
        child.type = 'click'
        sendIndex.value = 1;
    } else if (isKeyword) {
        sendIndex.value = 0;
    } else {
        sendIndex.value = 0;
    }

    await getSendData();
    const keyParts = key.split('_');
    targetId.value = keyParts[2] || '';
    const foundItem: any = tableData.value.find((item: any) => String(item.id) === String(targetId.value));
    if (hasImage) {
        await loadImageByMediaId(child.mediaId)
    } else if (isKeyword) {
        keyword.value = foundItem ? (foundItem.matchValue || foundItem.name || '') : '';
    } else {
        defaultText.value = foundItem ? (foundItem.replyContent || foundItem.name || '') : '';
    }
    menuRadio.value = '';
}

const openSend = async () => {
    // 当选择关键字时，自动设置菜单动作为"发送消息"
    if (!distinguish.value) {
        // 一级菜单
        menuList.value[activeMenuIndex.value].type = 'click'
    } else {
        // 二级菜单
        menuList.value[activeMenuIndex.value].subButtons[activeChildMenuIndex.value].type = 'click'
    }

    sendIndex.value = 0;

    if (sendIndex.value !== 1) {
        await getSendData()
    }
    sendModal.value = true
    selectedRowIndex.value = -1
    selectedRowData.value = null
}

const getSendData = async () => {
    tableLoading.value = true
    try {
        // 图片模式不需要请求数据源；关键字(0)需要；已去除文字类型
        if (sendIndex.value === 1) {
            tableData.value = []
            pageTotal.value = 0
            return
        }
        const res = await getAutoReplyPage({
            pageSize: pageSize.value,
            pageNum: pageNum.value,
            type: 2 // 关键字:2
        })
        if (res.code === '00000') {
            tableData.value = res.data.list
            pageTotal.value = res.data.total
        }
    } catch { } finally {
        tableLoading.value = false
    }
}

const currentChange = (val: number) => {
    pageNum.value = val
    getSendData()
}

const sizeChange = (val: number) => {
    pageSize.value = val
    pageNum.value = 1
    getSendData()
}

const handleRowClick = (row: any, index: number) => {
    selectedRowIndex.value = index
    selectedRowData.value = row
}

const delText = (e: number) => {
    // e === 0 删除文字，e === 1 删除关键字
    const clearCurrentKey = (prefix: string) => {
        if (!distinguish.value) {
            const curr = menuList.value[activeMenuIndex.value]
            if ((curr.key || '').startsWith(prefix)) curr.key = ''
        } else {
            const curr = menuList.value[activeMenuIndex.value].subButtons[activeChildMenuIndex.value]
            if ((curr.key || '').startsWith(prefix)) curr.key = ''
        }
    }
    if (e === 0) {
        // 清空文字并移除文字关联key（m_）
        defaultText.value = ''
        clearCurrentKey('m_')
    } else {
        // 清空关键字并移除关键字关联key（g_）
        keyword.value = ''
        clearCurrentKey('g_')
    }
}

const confirmSendSelection = () => {
    // 一级
    if (!distinguish.value) {
        // 关键字选择 -> click 类型
        keyword.value = selectedRowData.value.matchValue || selectedRowData.value.name
        menuList.value[activeMenuIndex.value].key = `g_${localStorage.getItem('lty-store-id')}_${selectedRowData.value.id}`
        menuList.value[activeMenuIndex.value].type = 'click'
    } else {//二级
        // 关键字选择 -> click 类型
        keyword.value = selectedRowData.value.matchValue || selectedRowData.value.name
        menuList.value[activeMenuIndex.value].subButtons[activeChildMenuIndex.value].key = `g_${localStorage.getItem('lty-store-id')}_${selectedRowData.value.id}`
        menuList.value[activeMenuIndex.value].subButtons[activeChildMenuIndex.value].type = 'click'
    }
    sendModal.value = false
}

function beforeSaveMenuList(_menuList: any[]) {
    // 深拷贝
    const deepList = JSON.parse(JSON.stringify(_menuList));
    for (const btn of deepList) {
        if (Array.isArray(btn.subButtons)) {
            for (const sub of btn.subButtons) {
                if (sub.type === 'miniprogram') {
                    // 页面地址/小程序路径 pagePath
                    if (sub.miniPagePath !== undefined) {
                        sub.pagePath = sub.miniPagePath
                    }
                    // 小程序URL 映射到url字段
                    if (sub.miniUrl !== undefined) {
                        sub.url = sub.miniUrl
                    }
                }
                // 清理辅助字段
                delete sub.miniPagePath
                delete sub.miniUrl
            }
        }
    }
    console.log(deepList, "deepList===");
    return deepList;
}

const handleSave = async () => {
    btnLoding.value = true
    try {
        console.log(menuList.value, "menuList.value=====");
        const submitMenu = beforeSaveMenuList(menuList.value)
        console.log(submitMenu, "submitMenu=====");
        const res = await customMenuCreate({
            buttons: submitMenu
        })
        if (res.code === '00000') {
            ElMessage.success('保存成功')
            getData()
        } else {
            ElMessage.error('保存失败')
        }
    } catch { } finally { btnLoding.value = false }
}

const sendChange = async (index: number) => {
    sendIndex.value = index

    // 当选择添加发送内容时，自动设置菜单动作为"发送消息"
    if (!distinguish.value) {
        // 一级菜单
        menuList.value[activeMenuIndex.value].type = 'click'
    } else {
        // 二级菜单
        menuList.value[activeMenuIndex.value].subButtons[activeChildMenuIndex.value].type = 'click'
    }

    if (index === 0) {
        await getSendData()
    } else if (index === 1) {
        // 获取图片素材进行回显
        const mediaId = !distinguish.value ? menuList.value[activeMenuIndex.value].mediaId : menuList.value[activeMenuIndex.value].subButtons[activeChildMenuIndex.value].mediaId
        await loadImageByMediaId(mediaId)
    }
}

const gzhAppId = ref('')
async function getAppId() {
    const res = await getGZHAuthorizerInfo({})
    if (res.code === '00000' && res.data) {
        gzhAppId.value = res.data.appId
    }
}

onMounted(() => {
    getData()
    getSendData()
    getAppId()
    sendIndex.value = 0;
})
</script>
<style scoped lang="scss">
.content {
    padding: 20px;
}

.menu-properties {
    display: flex;
}

.wechat {
    margin: 12px 32px 0 12px;
    height: 496px;
    width: 314px;
    border: 1px solid #eee;
    border-radius: 4px;
}

.menu-form {
    padding: 20px;
    margin-top: 12px;
    background-color: #f3f4f7;
    border-radius: 4px;
    float: left;
    height: 550px;
    min-width: 710px;
}

.wechat-header {
    height: 48px;
}

.wechat-body {
    height: 403px;
}

.wechat-footer {
    height: 42px;
    border-top: 1px solid #eee;
    display: flex;
}

.icon {
    flex: 0 0 52px;
    width: 52px;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    border-right: 1px solid #eee;

    img {
        width: 40%;
        height: 50%;
    }
}

.addMent {
    flex: 1 1;
    display: flex;
    height: 42px;
    position: relative;
    background: #fafbfc;
    border-radius: 0 0 4px 4px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);

    .itemMent {
        flex: 1 1 0;
        min-width: 0;
        border-right: 1px solid #eee;
        background: #fff;
        height: 42px;
        line-height: 42px;
        text-align: center;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
        text-align: center;
        font-size: 14px;
        color: #333;
        position: relative;

        &.itemMent-active {
            border: 1px solid #fb6638;
            z-index: 2;
        }

        .menu-name {
            max-width: 84px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            word-break: break-all;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
            display: -webkit-box;
        }

        .child-menu-container {
            position: absolute;
            left: 0;
            bottom: 60px;
            width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            z-index: 10;

            .child-menu-item {
                font-size: 12px;
                position: relative;
                border: 1px solid #eee;
                color: #666;
                transition: border-color 0.2s;

                &:hover {
                    border: 1px solid #fb6638;
                }

                &:hover .delChildIcon {
                    display: block;
                }
            }

            .child-menu-item-active {
                border: 1px solid #fb6638 !important;
                z-index: 3;
            }

            .delChildIcon {
                position: absolute;
                right: 3px;
                top: -11px;
                font-size: 16px;
                color: #ccc;
                display: none;
                cursor: pointer;
                transition: color 0.2s;
            }

            .child-menu-item,
            .add-child {
                width: calc(100% - 4px);
                height: 42px;
                background: #f7f7f7;
                border: 1px solid #eee;
                display: flex;
                align-items: center;
                justify-content: center;
                cursor: pointer;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                word-break: break-all;
                max-width: 100%;
                -webkit-line-clamp: 1;
                -webkit-box-orient: vertical;
                display: -webkit-box;
            }

            .child-menu-item {
                font-size: 12px;
                color: #666;
            }

            .add-child {
                font-size: 20px;
                color: #999;
            }
        }

        .delIcon {
            position: absolute;
            right: 3px;
            top: -11px;
            font-size: 16px;
            color: #ccc;
            display: none;
            cursor: pointer;
            transition: color 0.2s;
        }

        &:hover .delIcon {
            display: block;
        }
    }

    .itemMent:hover .delIcon {
        display: block;
    }
}

.add {
    flex: 1 1 0;
    border-right: 1px solid #eee;
    background: #fff;
    height: 42px;
    line-height: 42px;
    text-align: center;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    color: #ccc;
    background: #fff;
    border-right: 1px solid #eee;
}

.form-title {
    font-size: 14px;
    color: #333;
    margin-bottom: 20px;
}

.w270 {
    width: 270px;
}

.editor-box {
    width: 560px;
    background-color: #fff;
}

.wechat-wechat-editor {
    border: 1px solid #eee;
    border-radius: 4px;
    width: 100%;
    position: relative;
}

.editor-type {
    border-bottom: 1px solid #eee;
    display: grid;
    grid-template-columns: repeat(2, 1fr);

    .itemType {
        color: #999;
        height: 44px;
        padding: 0 25px;
        line-height: 44px;
        text-align: center;
        cursor: pointer;
    }

    .active {
        color: var(--el-color-primary);
    }
}

.editor-info {
    padding: 30px 60px;
    height: 270px;
    overflow: auto;
}

.editor-video {
    border: 1px dashed #ededed;
    border-radius: 4px;
    height: 260px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    color: #666;
    cursor: pointer;
}

/* 新增：图片上传预览 */
.image-preview-list {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
}

.image-preview-item {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.preview-img {
    width: 130px;
    height: 160px;
    border-radius: 4px;
    border: 1px solid #eee;
    margin-bottom: 4px;
}

.addIcon {
    font-size: 36px;
    color: #dad9d9;
    margin-bottom: 40px;
}

.textarea-info {
    height: 100%;

    :deep(.el-textarea__inner) {
        min-height: 200px !important;
    }
}

:deep(.el-form-item) {
    margin-bottom: 30px !important;
}

:deep(.el-input-group__append) {
    cursor: pointer;
    color: #333;
}

.delColor {
    margin-left: 10px;
    color: #fb6638;
    cursor: pointer;
}
</style>
